import axios, {AxiosResponse} from 'axios';
import authApi from "@/service/auth";
import {message} from 'ant-design-vue';
import router from '@/router';

// 创建一个axios实例
const instance = axios.create({
    // baseURL: import.meta.env.VITE_BASIC_URL,
    timeout: 15000,
    headers: {
        'Content-Type': 'application/json',
    },
    withCredentials: true,
});

instance.interceptors.response.use(response => {
    // 用户没有权限
    if (response.data.errCode === 60001) {
        message.error('登录已失效， 请重新登录！');
        router.push('/login');
    }
    return response.data;
}, error => {
    if (!error.response) {
        return Promise.reject(error)
    }
    // 用户没有权限
    if (error.data.errCode === 60001) {
        message.error('登录已失效， 请重新登录！');
        router.push('/login');
    }
    if (error.data.errCode != 0) {
        message.warning(error.data.msg);
    }
    // } else if (error.response.status === 500) {
    //     message.error(error.response.data.message);
    //     error = undefined;
    // } else if (error.response.status === 400) {
    //     if (error.response.data.errors) {
    //         message.error(error.response.data.errors.map((v: { message: any[]; }) => v.message.join("")));
    //         error = undefined;
    //     }
    // }
    return Promise.reject(error);
});


// 给请求头添加access_token
// const setHeaderToken = (isNeedToken: boolean) => {
//     if (isNeedToken) {
//         const token = authApi.getToken();
//         instance.defaults.headers.Authorization = `Bearer ${token}`
//     }
// }

// 有些api不需要用户授权使用，不携带access_token, 默认不携带
export const get = (url: string, params = {}, isNeedToken = false) => {
    url = '/api' + url;
    // if (import.meta.env.PROD) url = ".." + url;
    // setHeaderToken(isNeedToken);
    return instance({
        method: 'get',
        url,
        params,
    });
}

export const post = (url: string, data = {}, params = {}) => {
    // debugger;
    url = '/api' + url;
    // if (import.meta.env.PROD) url = ".." + url;
    // setHeaderToken(isNeedToken);
    const newUrl: string = encodeURI(url);
    return instance({
        method: 'post',
        url,
        data: data,
        params: params
    })
}


// 有些api不需要用户授权使用，不携带access_token, 默认不携带
export const mockGet = (url: string, params = {}, isNeedToken = false) => {
    url = '/mock' + url;
    // if (import.meta.env.PROD) url = ".." + url;
    // setHeaderToken(isNeedToken);
    return instance({
        method: 'get',
        url,
        params,
    });
}

export const mockPost = (url: string, params = {}, isNeedToken = false) => {
    url = '/mock' + url;
    // if (import.meta.env.PROD) url = ".." + url;
    // setHeaderToken(isNeedToken);
    const newUrl: string = encodeURI(url);
    return instance({
        method: 'post',
        url,
        data: params,
    })
}

export const apipost = (url: string, isNeedToken = false) => {
    url = '/api' + url;
    // if (import.meta.env.PROD) url = ".." + url;
    // setHeaderToken(isNeedToken);
    const newUrl: string = encodeURI(url);
    return instance({
        method: 'post',
        url
    })
}


// //上传
// export const upload = (url: string, params = {}, isNeedToken = true) => {
//     if (import.meta.env.PROD) url = ".." + url;
//     setHeaderToken(isNeedToken)
//     //instance.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
//     //const newUrl: string = encodeURI(url);
//     console.log('实例', instance.defaults.headers);
//     console.log('参数', params);
//     return instance({
//         method: 'post',
//         headers: {
//             "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
//         },
//         url,
//         data: params,
//     })
// }

// export const download = async (url: string, params = {}, isNeedToken = true) => {

//     const instance2 = axios.create({
//         //baseURL: '/api',
//         timeout: 15000,
//         headers: {
//             'Content-Type': 'application/json',
//         }
//     })

//     const token = authApi.getToken();
//     instance2.defaults.headers.Authorization = `Bearer ${token}`

//     if (import.meta.env.PROD) url = ".." + url;

//     const response = await instance2({
//         method: 'post',
//         responseType: 'blob',
//         url,
//         params,
//     })

//     convertRes2Blob(response);
// }

// const convertRes2Blob = (response: AxiosResponse<any, any>) => {
//     // 提取文件名
//     const fileName = "文件列表.xlsx";
//     // 将二进制流转为blob
//     const blob = new Blob([response.data], { type: 'application/octet-stream' })
//     if (typeof window.navigator?.msSaveBlob !== 'undefined') {
//         // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
//         window.navigator?.msSaveBlob(blob, decodeURI(fileName))
//     } else {
//         // 创建新的URL并指向File对象或者Blob对象的地址
//         const blobURL = window.URL.createObjectURL(blob)
//         // 创建a标签，用于跳转至下载链接
//         const tempLink = document.createElement('a')
//         tempLink.style.display = 'none'
//         tempLink.href = blobURL
//         tempLink.setAttribute('download', decodeURI(fileName))
//         // 兼容：某些浏览器不支持HTML5的download属性
//         if (typeof tempLink.download === 'undefined') {
//             tempLink.setAttribute('target', '_blank')
//         }
//         // 挂载a标签
//         document.body.appendChild(tempLink)
//         tempLink.click()
//         document.body.removeChild(tempLink)
//         // 释放blob URL地址
//         window.URL.revokeObjectURL(blobURL)
//     }
// }
export default instance

